import 'dart:math';

import 'package:enterprise_v6_app/app/components/custom_refresh.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/core/utils/scan_util.dart';
import 'package:enterprise_v6_app/app/data/entities/application/basic_information/equip_instrument_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/inspec/plan_associated_tasks_entity.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';

class PlanUnitController extends GetxController {
  /// 计划id
  String planId = Get.arguments as String;

  /// 列表刷新key
  final GlobalKey<CustomEasyRefreshListState> globalKey = GlobalKey();

  /// 扫码操作
  Future<void> scan(PlanAssociatedTasksEntity item) async {
    final Map<String, dynamic> deviceMap = await ScanUtil.scanUnitQRReturnMap();
    if (deviceMap.isEmpty) {
      return;
    }
    // 墨水瓶扫码接口判断是否为当前单元
    final res = await HttpUtil().generateGetRequest<List<EquipInstrumentEntity>>(
      Interface.inkBottleScanning,
      queryParameters: {
        'deviceNo': deviceMap['ID'],
        'checkCode': deviceMap['time'],
        'unitId': item.riskUnitId,
      },
    ).execute();
    res.onSuccess((result) {
      if (result.data != null && result.data!.isNotEmpty) {
        final double randomNumber = Random().nextDouble();
        // 设置百分之五十的几率进入人脸识别页面
        if (randomNumber < 0.5) {
          Get.toNamed(AppRoutes.faceAuth)?.then((value) {
            /// 从此页面返回，会返回一个 bool?
            /// - true：成功
            /// - false：失败
            /// - null：未识别
            if (value == true) {
              toTask(item.riskUnitId!);
            } else if (value == false) {
              AppToast.showWarning('人脸识别失败');
            } else {
              AppToast.showWarning('未识别');
            }
          });
        } else {
          toTask(item.riskUnitId!);
        }
      } else {
        AppToast.showWarning('请扫描本单元二维码');
      }
    });
  }

  /// 列表接口
  Future<List<PlanAssociatedTasksEntity>> getListData(int pageNum, int pageSize) async {
    // 获取列表接口
    final res = await HttpUtil().generateGetRequest<List<PlanAssociatedTasksEntity>>(
      Interface.getUnitListByPlanId,
      queryParameters: {'planId': planId},
    ).execute();
    List<PlanAssociatedTasksEntity>? data;
    res.onSuccess((result) {
      if (result.data != null) {
        data = result.data!;
      }
    });
    return data ?? [];
  } // 获取列表数据

  ///进入任务
  void toTask(String riskUnitId) {
    Get.toNamed(AppRoutes.runTaskDetail, arguments: {'unitId': riskUnitId, 'planId': planId, 'type': 1})?.then((value) {
      onRefresh();
    });
  }

  /// 刷新列表
  void onRefresh() {
    globalKey.currentState!.onRefresh();
    update();
  }
}
